package com.sheet.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description
 *
 * @Author IronSheet
 * @Date 2022/3/2 2:25
 */
@RestController
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/goods/{id}")
    public String callProvider(@PathVariable("id") int id){
        List<ServiceInstance> instances = discoveryClient.getInstances("nacos-provider");
        if (instances == null || instances.size() <= 0) {
            return null;
        }
        ServiceInstance serviceInstance = instances.get(0);
        String host = serviceInstance.getHost();
        int port = serviceInstance.getPort();
        System.out.println("ip:" + host + ",port:" + port);
        String url = "http://" + host + ":" + port + "/goods/findOne/" + id;

        String str = restTemplate.getForObject(url, String.class);
        System.out.println(str);
        return str;
    }
}
